/*
 * @Date: 2023-03-05 14:38:16
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-05 14:59:19
 * @FilePath: \A19\backend\src\api\SourceManage\ApiDeleteFile.ts
 */
import { ApiCall } from "tsrpc";
import { ReqDeleteFile, ResDeleteFile } from "../../shared/protocols/SourceManage/PtlDeleteFile";
import { Global } from "../../Global";
import { findFolder } from "../../utils/FindCurrentFolder";
import deleteFile from "../../utils/deleteFile";
import { Folder } from "../../utils/Folder";

export default async function (call: ApiCall<ReqDeleteFile, ResDeleteFile>) {
    // TODO
    const root = await Global.collection('folders').findOne({
        course:call.req.course
    })
    if(!root) return call.error('课程不存在')

    const folder = findFolder(call.req.path,root)
    if(!folder) return call.error('文件夹不存在')

    const index = folder.files.findIndex(f => f.url === call.req.url)
    if(index === -1) return call.error('文件不存在')

    try {
        await deleteFile(Folder.sources,call.req.url)
    } catch (error) {
        if(error instanceof Error){
            call.error(error.message)
        }
    }
    
    folder.files.splice(index,1)

    await Global.collection('folders').updateOne({
        course:call.req.course
    },{
        $set:{
            folders:root.folders,
            files:root.files
        }
    })

    call.succ({
        files:folder.files,
        folders:folder.folders.map(f => f.name)
    })
}